package com.bang.daybreak.security.config.handler;

import com.bang.daybreak.common.util.JacksonUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * <p>
 *     用户登录失败。
 * </p>
 *
 * @version 1.0
 * @author: wdj
 * @date: 2019/8/11 0011 下午 17:23
 */
@Component
public class IdentityAuthenticationFailureHandler implements AuthenticationFailureHandler {
    /**
     * 登录失败，给用户返回数据.
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse
            , AuthenticationException e) throws IOException, ServletException {
        String username = httpServletRequest.getParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY);
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        map.put("username",username);
        map.put("timestamp", System.currentTimeMillis());
        map.put("httpCode", HttpStatus.BAD_REQUEST.value());
        map.put("error", "USER_LOGIN_FAILED");
        map.put("msg", "用户账号或密码错误");
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.setStatus(400);
        httpServletResponse.getWriter().write(JacksonUtils.toJson(map));

    }
}
